import Pools from './pools';
import { hasOwn } from '../utils/valid';
import Creater from './creater';
import { FocusBinding } from './focus';
import Service from '../utils/service';
import { getPopupStr } from '../utils/tools';

/**
 * 根据路由创建视图区域对象
 */
export default class Views {
  /**
   * 焦点组
   */
  layers: { rootPopup: Pools;[key: string]: Pools };
  /**
   * 焦点所处弹层标记
   */
  popSign: string;
  /**
   * 当前层级视图组成，默认default，命名视图对应路由名称
   */
  routeViews: { [key: string]: { [key: string]: Views } };
  /**
   * 焦点所处视图标记
   */
  viewSign: string;
  /**
   * 父级视图
   */
  parent?: Views;
  /**
   * 关联元素信息
   */
  __baseView__?: Creater;

  constructor(parent?: Views) {
    this.layers = { rootPopup: new Pools() };
    this.popSign = '';
    this.routeViews = {};
    this.viewSign = '';
    this.parent = parent;
  }

  /**
   * 获取指定弹层对象
   * @param {String} popup 弹层标记名称
   * @returns
   */
  get getLayer() {
    return (popup?: string): Pools | null => {
      let layer = getPopupStr(popup);
      return this.layers[layer] || null;
    }
  }
  /**
   * 获取焦点池对象，如果没有则创建新焦点池
   * @param {String} sign 标记名称
   * @returns Array
   */
  get checkOrCreateLayer() {
    return (popup?: string) => {
      let layer = getPopupStr(popup);
      if (hasOwn(this.layers, layer)) {
        if (this.layers[layer] instanceof Pools) {
          return this.layers[layer];
        } else {
          // 可能由于手动修改导致
          throw `获取${popup}弹层失败`;
        }
      } else {
        return (this.layers[layer] = new Pools());
      }
    }
  }

  /**
   * 检测默认标记变量
   * @param {String} sign 分组标记名称
   * @param {String} popup 弹层标记名称
   * @returns Boolean
   */
  get checkSignFlag() {
    return (sign: string, popup: string) => {
      let layer = this.getLayer(popup);
      let flag = layer ? layer.checkSign(sign) : false;
      return flag;
    }
  }

  /**
   * 注册焦点
   * @param {Object} creater 焦点对象
   */
  get registeLayer() {
    return (creater: Creater) => {
      let layer = this.checkOrCreateLayer(creater.popup);
      creater.__pools__ = layer;
      layer.registePool(creater);
    }
  }
  /**
   * 注册路由节点对象
   * @param {*} BaseView
   */
  get registeEl() {
    return (routeEl: HTMLElement, routeVpath: string, view: Views, service: Service) => {
      // 获取父view对象
      const viewBinding = { value: routeVpath } as FocusBinding;
      this.__baseView__ = new Creater("views", routeEl, viewBinding, service);
      this.__baseView__.__views__ = view;
    }
  }
}
